package com.pro.common.pay.third.service;

import cn.hutool.core.util.ObjUtil;
import cn.hutool.json.JSONUtil;
import com.alipay.api.*;
import com.alipay.api.domain.AlipayTradePrecreateModel;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePrecreateRequest;
import com.alipay.api.response.AlipayTradePrecreateResponse;
import com.pro.common.api.enums.EnumPaymentResponseType;
import com.pro.common.api.exception.BusinessException;
import com.pro.common.api.exception.BusinessNoTranslateException;
import com.pro.common.api.model.request.pay.PaymentNotifyData;
import com.pro.common.api.model.request.pay.PaymentResponse;
import com.pro.common.api.model.request.pay.PaymentUserDetail;
import com.pro.common.api.pay.intf.IPaymentService;
import com.pro.common.api.pay.model.db.PayMerchant;
import com.pro.common.api.pay.model.dto.PaymentParamDTO;
import com.pro.common.pay.third.enums.EnumPayMerchantPlatform;
import com.pro.framework.api.util.DateUtils;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDateTime;
import java.util.LinkedHashMap;

@Service
@Getter
@Slf4j
public class AliPayService implements IPaymentService {


    private final String merchantPlatform = EnumPayMerchantPlatform.ali.name();

    @Override
    public PaymentResponse payment(PaymentParamDTO dto, PaymentUserDetail userDetail, PayMerchant payMerchant) {

        String notifyUrl = dto.getNotifyUrl();
        BigDecimal orderAmount = dto.getOrderAmount();
        String no = dto.getNo();
        try {
            // 初始化SDK
            DefaultAlipayClient alipayClient = new DefaultAlipayClient(getCertAlipayRequest(payMerchant));
            // 构造请求参数以调用接口
//            AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();
//            AlipayTradePagePayModel model = new AlipayTradePagePayModel();
            AlipayTradePrecreateRequest request = new AlipayTradePrecreateRequest();
            AlipayTradePrecreateModel model = new AlipayTradePrecreateModel();
            model.setOutTradeNo(no);
            model.setTotalAmount(orderAmount.setScale(2, RoundingMode.HALF_UP).toString());
            model.setSubject(ObjUtil.defaultIfBlank(dto.getSubject(), "神蚁订单"));
            model.setProductCode("QR_CODE_OFFLINE");
//            model.setProductCode("FAST_INSTANT_TRADE_PAY");
            request.setBizModel(model);
            request.setNotifyUrl(notifyUrl);
//        AlipayTradePagePayResponse response = alipayClient.pageExecute(request, "POST");
//            AlipayTradePagePayResponse response = alipayClient.pageExecute(request,"GET");
            AlipayTradePrecreateResponse response = alipayClient.certificateExecute(request);
            log.info("response:{}", response);
            if (!response.isSuccess()) {
                throw new BusinessNoTranslateException(response.getMsg());
            }
            String value = response.getQrCode();
            return PaymentResponse.builder()
                    .payMethod(dto.getPayMethod())
                    .no(dto.getNo())
                    .orderAmount(dto.getOrderAmount())
                    .type(EnumPaymentResponseType.URL)
                    .value(value)
                    .expireTime(DateUtils.toTimestampMillis(LocalDateTime.now().plusMinutes(10)))
                    .build();
        } catch (AlipayApiException e) {
            log.error("支付宝调用失败：{}", e.getMessage());
            throw new BusinessException("支付宝调用失败", e.getMessage());
        }
    }

    @Override
    public PaymentNotifyData paymentNotifyRead(String params, PayMerchant payMerchant) {
        try {
            //noinspection unchecked
            LinkedHashMap<String, String> notifyMap = JSONUtil.toBean(params, LinkedHashMap.class);
            String alipayPublicCertPath = JSONUtil.toBean(payMerchant.getExtendConfigJson(), CertAlipayRequest.class).getAlipayPublicCertPath();

            boolean signVerified = AlipaySignature.rsaCertCheckV1(notifyMap, alipayPublicCertPath, "UTF-8", "RSA2");
            if (!signVerified) {
                throw new BusinessException("支付宝回调验签失败");
            }
            String outTradeNo = notifyMap.get("out_trade_no"); // 商户订单号
            String tradeStatus = notifyMap.get("trade_status"); // 支付状态
            String tradeNo = notifyMap.get("trade_no"); // 支付宝交易号
            String totalAmount = notifyMap.get("total_amount");
            PaymentNotifyData.PaymentNotifyDataBuilder data = PaymentNotifyData.builder()
                    .no(outTradeNo)
                    .outId(tradeNo)
                    .payAmount(new BigDecimal(totalAmount));

            if ("TRADE_SUCCESS".equals(tradeStatus) || "TRADE_FINISHED".equals(tradeStatus)) {
                log.info("支付宝支付成功，订单号：{}", outTradeNo);
                data.statusSuccess(true);
            } else {
                log.warn("支付宝支付未成功，状态：{}", tradeStatus);
                data.statusSuccess(false);
            }

            return data.build();

        } catch (Exception e) {
            log.warn("支付宝回调处理异常 {}", JSONUtil.toJsonStr(params), e);
            throw new BusinessException("支付宝回调处理异常_", e.getMessage());
        }
    }


    @Override
    public String paymentNotifyReturn(Boolean end) {
        return end ? "SUCCESS" : "FAIL";
    }

//    private static CertAlipayRequest getAlipayConfig()  {
//        String url = "https://openapi.alipay.com/gateway.do";
//        String appId = "2021005157600970";
////        String alipayPublicKey = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAtQvuptHgYIcBCTL26mT9NklcBt05eirqybYqJ23GEmeqxoc6FyyEOvrAG5StTb9pohFB24/Wyl01LAxi6advEDVd2XL7yI/+Qh5az8+MTjQubOf9JhinX+6iGhyqthayvfh6W6GhgQ0XVhU+9OWMcg77SWT3E0ANHrwrnVafHnCABMDHQrgSeTkI5QluJLw05Guy5NPyr66V6bi07Ob0cZf5rZipcM7CA34yT9tgBGTElUWdeveJybLdgU54p/HdkjuBKiN7onYfAHCR//rto2TUhTTvsE0mcr/3E4LxN4YQGcLE0QTjjlEOQWIo/OaQnp56Fl2H0XOTqJAFKJek8wIDAQAB";
//        String privateKey = "MIIEowIBAAKCAQEAirESK3XILh76TIgP2xaXOuRpRxCkmPPytZGck6eeu2Y8nU7dHpzjr0+Ym4yHZOFcbAVYBd08kKEpxPGHsv7cItIgTzEQf+yg4DlaegvTDStnvLpWmRYFwNa5cLk4nHU0SJzKq7fiv5hQDsscUvlqhcv08m3YKRURTgePnzNG1yhk50ZVUSJxU0lERLxkYW+llinw1nRMJI/PEV7hrcQksJ17MRKCAyokhBYHMchhLkDM7R+6+W88A9NY+5eOHCKn/ugjOQMrsMA4pyoDQGbKz4SFQCWTveClz74EGFHj/8fD12TEyARst2ahn7ZlO8NVXsnba6loCp2K6348TXBeawIDAQABAoIBAGM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3Ai5KN553VXtcQLMNOJSlbAmmjBQOXcHNg18D0gtpdkydsLMbppchmFtmpkiVVPdRyCQwQxgRNzNHIoBLaaR6wD2xsI+hze5qzmmcu/j5Q5YGXQS2rmtoMKQEc3kOZefrrSr7BczkVpx3W0fm3";
//        String rootCertPath = "D:/lzb/baoyi-cloud/platform/1-docs/cert/alipayRootCert.crt";
//        String certPath = "D:/lzb/baoyi-cloud/platform/1-docs/cert/appCertPublicKey_2021005157600970.crt";
//        String alipayPublicCertPath = "D:/lzb/baoyi-cloud/platform/1-docs/cert/alipayCertPublicKey_RSA2.crt";
//        CertAlipayRequest certAlipayRequest = new CertAlipayRequest();
////        AlipayConfig alipayConfig = new AlipayConfig();
//       certAlipayRequest.setServerUrl(url);
//       certAlipayRequest.setAppId(appId);
//       certAlipayRequest.setPrivateKey(privateKey);
//       certAlipayRequest.setFormat("json");
////     certAlipayRequest.setAlipayPublicKey(alipayPublicKey);
//       certAlipayRequest.setCharset("UTF-8");
//       certAlipayRequest.setSignType("RSA2");

    /// /        D:/cert/appCertPublicKey_2021005157600970.crt
    /// /        D:/cert/alipayCertPublicKey_RSA2.crt
//       certAlipayRequest.setCertPath(certPath);
//       certAlipayRequest.setAlipayPublicCertPath(alipayPublicCertPath);
//       certAlipayRequest.setRootCertPath(rootCertPath);
//        return certAlipayRequest;
//    }
    private static CertAlipayRequest getCertAlipayRequest(PayMerchant payMerchant) {
        /*
         * {
         *   "rootCertPath": "/cert/ali/alipayRootCert.crt",
         *   "certPath": "/cert/ali/appCertPublicKey.crt",
         *   "alipayPublicCertPath": "/cert/ali/alipayCertPublicKey_RSA2.crt"
         * }
         */
        CertAlipayRequest cert = JSONUtil.toBean(payMerchant.getExtendConfigJson(), CertAlipayRequest.class);
        cert.setAppId(payMerchant.getAppId());
        cert.setServerUrl(payMerchant.getPaymentRequestUrl());
        cert.setPrivateKey(payMerchant.getPaymentPrivateKey());
        cert.setFormat("json");
        cert.setCharset("UTF-8");
        cert.setSignType("RSA2");
        return cert;
    }


    public static void main(String[] args) {
        System.out.println("{\"rootCertPath\":\"/cert/ali/alipayRootCert.crt\",\"certPath\":\"/cert/ali/appCertPublicKey.crt\",\"alipayPublicCertPath\":\"/cert/ali/alipayCertPublicKey_RSA2.crt\"}");
    }

}
